/**
 * @description websocktet长链接常用操作封装
 */
const socket = {
  // socket连接对象
  websockt: null,
  // socket链接地址
  ws_url: null,
  // 开启标识
  socket_open: false,
  // 心跳timer标识
  hearbeat_timer: null,
  // 心跳发送频率
  hearbeat_interval: 5000,
  // 是否自动重连
  is_reconnect: true,
  // 重连次数
  reconnect_count: 3,
  // 已发起重连次数
  reconnect_current: 1,
  // 重连timer标识
  reconnect_timer: null,
  // 重连频率
  reconnect_interval: 4000,
  /**
   * @description 初始化连接
   * @param { object } params 初始化连接参数
   *        { function } success 连接成功回调
   *        { function } error 连接失败回调
   *        { function } close 关闭连接回调
   *        { function } receive 接收消息回调
   *        { string } url websocket连接地址
   */
  connect: (params) => {
    if (!('WebSocket' in window)) {
      console.log('您的浏览器不支持WebSocket')
      return null
    }
    if (socket.websockt && socket.websockt.readyState === 1) return
    socket.websockt = new WebSocket(params.host || socket.ws_url)
    socket.websockt.onmessage = (e) => {
      const message = e.data
      if (params.receive) params.receive(message)
    }

    // 关闭连接
    socket.websockt.onclose = (e) => {
      console.log('websocket连接关闭')
      clearInterval(socket.hearbeat_interval)
      socket.socket_open = false
      socket.websockt = null
      if (params.close) params.close()
      // 判断是否需要重新连接，并记录重连次数
      if (socket.is_reconnect) {
        socket.reconnect_timer = setInterval(() => {
          if (socket.reconnect_current > socket.reconnect_count) {
            clearInterval(socket.reconnect_timer)
            return
          }
          socket.reconnect_current++
          socket.reconnect(params)
        }, socket.reconnect_interval)
      }
    }
    // 连接成功
    socket.websockt.onopen = () => {
      console.log('websocket连接成功')
      clearInterval(socket.reconnect_timer)
      socket.socket_open = true
      socket.is_reconnect = true
      socket.heartbeat()
      if (params.success) params.success()
    }

    // 连接发生错误
    socket.websockt.onerror = () => {
      console.log('websocket连接错误')
      if (params.error) params.error()
    }
    return new Promise((resolve) => {
      resolve(params.token)
    })
  },

  /**
   * @description 发送消息
   * @param { string } data 发送消息的数据字符串对象
   * @param { function} callback 发送成功后自定义回调
   */
  send: (data, callback = null) => {
    // 开启状态直接发送
    if (socket.websockt && socket.websockt.readyState === socket.websockt.OPEN) {
      socket.websockt.send(JSON.stringify(data))
      if (callback) {
        callback()
      }
    } else if (
      // 正在开启状态，则等待1s后重新调用
      socket.websockt &&
      socket.websockt.readyState === socket.websockt.CONNECTING
    ) {
      setTimeout(() => {
        socket.send(data, callback)
      }, 1000)
    }
  },

  /**
   * @description 心跳检查
   */
  heartbeat: () => {
    if (socket.hearbeat_timer) {
      clearInterval(socket.hearbeat_timer)
    }
    socket.hearbeat_timer = setInterval(() => {
      // var data = {};
      // socket.send(data);
    }, socket.hearbeat_interval)
  },

  /**
   * @description 主动关闭连接
   * @param { function } callback 主动断开连接后的回调
   */
  close: (callback) => {
    console.log('websocket断开连接')
    clearInterval(socket.hearbeat_interval)
    socket.is_reconnect = false
    socket.websockt.close()
    if (callback) callback()
  },

  /**
   * @description 重新连接
   * @param { object } params 连接参数
   */
  reconnect: (params) => {
    console.log('websocket重新连接', '次数' + socket.reconnect_current)
    if (socket.websockt && socket.socket_open) {
      socket.websockt.close()
    }
    socket.connect(params)
  }
}
export { socket }
